package org.xiaoyu.rpc.registry.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import lombok.extern.slf4j.Slf4j;
import org.xiaoyu.rpc.common.constant.SystemPropertiesKey;
import org.xiaoyu.rpc.registry.Registry;
import org.xiaoyu.rpc.registry.RegistryFactory;

import java.util.Properties;

/**
 * Created By Have
 * 2021/7/12 16:23
 */
@Slf4j
public class NacosRegistrySingletonFactory implements RegistryFactory {
    private volatile Registry INSTANCE;

    @Override
    public Registry createRegistry(Properties properties) {
        if (INSTANCE == null) {
            synchronized (this) {
                if (INSTANCE == null) {
                    String registryAddr = properties.getProperty(SystemPropertiesKey.REGISTER_ADDR);
                    try {
//                        System.out.println(registryAddr);
                        NamingService namingService = NacosFactory.createNamingService(registryAddr);
                        INSTANCE = new NacosRegistry(properties, new NacosNamingServiceWrapper(namingService));
                    } catch (NacosException e) {
                        if (log.isErrorEnabled()) {
                            log.error("connect nacos fail", e);
                        }
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return INSTANCE;
    }
}
